package com.woniu.servicepassengeruser.service;



import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.internalcommon.constant.IdentityConstants;
import com.woniu.internalcommon.constant.TokenConstants;
import com.woniu.internalcommon.dto.OrderInfo;
import com.woniu.internalcommon.response.TokenResponse;
import com.woniu.internalcommon.util.JwtUtils;
import com.woniu.internalcommon.util.RedisPrefixUtils;
import com.woniu.servicepassengeruser.mapper.PassengerUserMapper;
import com.woniu.internalcommon.constant.CommonStatusEnum;
import com.woniu.internalcommon.dto.PassengerUser;
import com.woniu.internalcommon.dto.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private PassengerUserMapper passengerUserMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public ResponseResult loginOrRegister(String passengerPhone){
//        System.out.println("user service被调用，手机号："+passengerPhone);

        // 根据手机号查询用户信息
        Map<String,Object> map = new HashMap<>();
        map.put("passenger_Phone",passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(map);

        // 判断用户信息是否存在
        if (passengerUsers.size() == 0){
            // 如果不存在，插入用户信息
//            PassengerUser passengerUser = new PassengerUser();
//            passengerUser.setPassengerName("张三");
//            passengerUser.setPassengerGender((byte) 0);
//            passengerUser.setPassengerPhone(passengerPhone);
//            passengerUser.setState((byte) 0);
//
//            LocalDateTime now = LocalDateTime.now();
//            passengerUser.setGmtCreate(now);
//            passengerUser.setGmtModified(now);
//
//            passengerUserMapper.insert(passengerUser);
            return ResponseResult.fail(666,"没有此用户，需注册");
        }else{
            return ResponseResult.success();
        }
    }
    public ResponseResult userRegister(String passengerName, String passengerPhone, Byte passengerGender) {
        // 1. 校验
        PassengerUser passengerUser = new PassengerUser();
        if (StringUtils.isAnyBlank(passengerName, passengerPhone, passengerGender.toString())) {
            return ResponseResult.fail(500,"请填写完整信息");
        }
        if (passengerPhone.length() != 11 || !passengerPhone.matches("\\d+")) {
            return ResponseResult.fail(500,"电话号码长度非法");
        }
        passengerUser.setPassengerName(passengerName);
        passengerUser.setPassengerGender(passengerGender);
        passengerUser.setState((byte) 0);

        LocalDateTime now = LocalDateTime.now();
        passengerUser.setGmtCreate(now);
        passengerUser.setGmtModified(now);
        // 2. 检查号段（2024年最新规则）
        String segment = passengerPhone.substring(0, 3);
        switch (segment) {
            // 中国移动
            case "134": case "135": case "136": case "137": case "138": case "139":
            case "147": case "148": // 物联网号段
            case "150": case "151": case "152": case "157": case "158": case "159":
            case "172": case "178": // 4G号段
            case "182": case "183": case "184": case "187": case "188":
            case "195": case "197": case "198":
//                return ResponseResult.success();

            // 中国联通
            case "130": case "131": case "132":
            case "145": case "146": // 物联网号段
            case "155": case "156":
            case "166": // 虚拟运营商
            case "171": case "175": case "176": case "177":
            case "185": case "186":
            case "196":

//                return ResponseResult.success();

            // 中国电信
            case "133":
            case "149": // 物联网号段
            case "153":
            case "173": case "174":  case "179":
            case "180": case "181": case "189":
            case "191": case "193": case "199":
//                return ResponseResult.success();

            // 中国广电（192）
            case "192":
//                return ResponseResult.success();

            // 其他虚拟运营商/卫星通信等（按需扩展）
            case "162": case "165": case "167": case "170":
                passengerUser.setPassengerPhone(passengerPhone);
                passengerUserMapper.insert(passengerUser);
                PassengerUser passengerUser1=(PassengerUser) getUserByPhone(passengerPhone).getData();
                String accessToken = JwtUtils.generatorToken(passengerPhone, IdentityConstants.PASSENGER_IDENTITY, TokenConstants.ACCESS_TOKEN_TYPE);
                String refreshToken = JwtUtils.generatorToken(passengerPhone, IdentityConstants.PASSENGER_IDENTITY ,TokenConstants.REFRESH_TOKEN_TYPE);

                // 将token存到redis当中
                String accessTokenKey = RedisPrefixUtils.generatorTokenKey(passengerPhone , IdentityConstants.PASSENGER_IDENTITY , TokenConstants.ACCESS_TOKEN_TYPE);
                stringRedisTemplate.opsForValue().set(accessTokenKey , accessToken , 30, TimeUnit.DAYS);
                System.out.println("  case \"162\": case \"165\": case \"167\": case \"170\":");
                String refreshTokenKey = RedisPrefixUtils.generatorTokenKey(passengerPhone , IdentityConstants.PASSENGER_IDENTITY , TokenConstants.REFRESH_TOKEN_TYPE);
                stringRedisTemplate.opsForValue().set(refreshTokenKey , refreshToken , 31, TimeUnit.DAYS);
                TokenResponse tokenResponse = new TokenResponse();
                tokenResponse.setAccessToken(accessToken);
                tokenResponse.setRefreshToken(refreshToken);
                return ResponseResult.success(tokenResponse);
            default:
                return ResponseResult.fail(500,"电话号码格式非法");
        }
    }
    /**
     * 根据手机号查询用户信息
     * @param passengerPhone
     * @return
     */
    public ResponseResult getUserByPhone(String passengerPhone){
        // 根据手机号查询用户信息
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("passenger_phone",passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(map);
        if (passengerUsers.size() == 0){
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_EXISTS.getCode(),CommonStatusEnum.USER_NOT_EXISTS.getValue());
        } else {
            PassengerUser passengerUser = passengerUsers.get(0);
            return ResponseResult.success(passengerUser);

        }
    }

    /**
     * 查询所有用户
     * @return
     */
    public ResponseResult<Page<PassengerUser>> selectAll(Integer  current, Integer size ) {
        // 创建分页对象，第current页，每页size条记录
        Page<PassengerUser> userPage = new Page<>(current, size);
        // 执行分页查询
        Page<PassengerUser> userPageResult = passengerUserMapper.selectPage(userPage, null);
        return ResponseResult.success(userPageResult);
    }
}